<?php

namespace Admin\Controller;

use Base\BackController;

class CloserCommodityController extends BackController {

    //用户列表
    public function index() {
        $this->user_model = M('bh_closet_commodity');
        $join = 'left join eosi_weixin_user ON eosi_bh_closet_commodity.uid = eosi_weixin_user.id';
        $joinad ='left join eosi_bh_type ON eosi_bh_closet_commodity.type = eosi_bh_type.id';
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
        $map=array();
        if($_GET['nickname']!=''){
            $map['eosi_weixin_user.nickname']=array('like', '%'.$_GET['nickname'].'%');
        }
        if($_GET['aname']!=''){
             $map['eosi_bh_closet_commodity.name']=array('like', '%'.$_GET['aname'].'%');
        }
        if($_GET['bname']!='' && $_GET['bname']!= 1){
             $map['eosi_bh_type.id']=$_GET['bname'];
        }
        if($_GET['memo']!=''){
             $map['eosi_bh_closet_commodity.memo']=array('like', '%'.$_GET['memo'].'%');
        }
        if($_GET['ano']!=''){
             $map['eosi_bh_closet_commodity.no']=array('like', '%'.$_GET['ano'].'%');
        }
        if($_GET['status']!=''){
             $map['eosi_bh_closet_commodity.status']=$_GET['status'];
        }
        else {
            $_GET['status']='';
        }

        $map['eosi_bh_closet_commodity.uid']=999;
        // var_dump($map);
        //任务总数
        $total = $this->user_model->join($join)->join($joinad)->where($map)->count();
        //每页条数
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        //实例化分页类
        $page = new \Admin\ORG\PageNew($total, $listRows, '');
        // if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        // }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');     
        $ab ='eosi_bh_closet_commodity.img as aimg,eosi_bh_type.img as bimg,
                eosi_bh_closet_commodity.name as aname,eosi_bh_type.name as bname,
                eosi_weixin_user.nickname,eosi_bh_closet_commodity.*';
        $dataList = $this->user_model->join($join)->join($joinad)->where($map)->order('eosi_bh_closet_commodity.show_order desc, eosi_bh_closet_commodity.update_time desc')->limit("$page->firstRow,$page->listRows")->Field($ab)->select();
        // dump($dataList);
        $this->new_type =M('bh_type');
        $dataListopt =$this->new_type->select();
        //数据处理
        foreach ($dataList as $k => $value){
            $cctime=$value['create_time'];
            //状态
            if ($value['status'] == 1) {
                $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\" >" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" title=\"禁用\" style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }else{
                $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" title=\"启用\"  style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);
            $value['dh_date'] = date('Y-m-d ', $value['dh_date']);
            $value['dh_date'] = explode('-', $value['dh_date']);
            $c = $value['dh_date'][0];
            $a = $value['dh_date'][1];
            $a = preg_replace('/^0/', '', $a);
            $b = $value['dh_date'][2];
            $b = preg_replace('/^0/', '', $b);
            $value['dh_date'] =$c.'.'.$a.'.'.$b;
            // $map['eosi_bh_calendar.year']=array('like',$_GET['bname'][0]);
            // $map['eosi_bh_calendar.month']=array('like',$a);
            // $map['eosi_bh_calendar.day']=array('like',$b);

            $value['img'] =  ic_getUploadImgFullPath('commodity',$value['aimg'],$cctime);
            $value['s_img'] = ic_getThumbImg($value['img'],'s_');
            
            $dataList[$k] = $value;
            $imgchild = array();
            if(ic_checkUnEmpty($value['sub_imgs'])){
                $value['sub_imgs'] =explode(',',$value['sub_imgs']); 
                foreach ($value['sub_imgs'] as $key => $v) {
                    $v =  ic_getUploadImgFullPath('commodity',$v,$cctime);
                    $imgchild[$key]=array();
                    $imgchild[$key]['img'] = $v;
                    $imgchild[$key]['s_img'] = ic_getThumbImg($v,'s_');
                    // $imgchild[$key] = $v;
                }
            }
            $dataList[$k]['sub_imgs_arr'] = $imgchild;
        }
        
        $this->assign('_listopt', $dataListopt);
        $this->assign('_list', $dataList);
        $this->assign('bname_id', $_GET['bname']);
        $this->assign('nickname', $_GET['nickname']);
        $this->assign('aname', $_GET['aname']);
        $this->assign('memo', $_GET['memo']);
        $this->assign('ano', $_GET['ano']);
        $this->assign('selected_status', $_GET['status']);
        $this->assign('groupName', '商品管理');
        $this->assign('moduleName', '商品列表');
        $this->assign('actionName', '商品概览');
        // $this->assign('nickname',$array['nickname']);
        $this->display();
    }
    // 状态修改
    public function status_change(){
        try {
            $type = I('type');
            $userid = I('id');
            if (empty($type) || empty($userid)) {
                $ajaxdata['info'] = '丢失参数';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            if ($type == '有效')
                $str = '启用用户';
            if ($type == '无效')
                $str = '禁用用户';
            $data = array();
            $data['id'] = $userid;
            if ($type == '有效') {
                $data['status'] = 0;
            }
            if ($type == '无效') {
                $data['status'] = 1;
            }
            $falg=M('bh_closet_commodity')->save($data); 
            if(!$falg){
                $ajaxdata['info'] = '网络故障提交失败,请稍候再试';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            $ajaxdata['info'] = 'ok';
            $ajaxdata['status'] = 1;
            $this->ajaxReturn($ajaxdata);
        } catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }
    //编辑规则
        public function editRule() {
            if(stripos($_SERVER['HTTP_REFERER'], "CloserCommodity/index")>0){
                ic_rememberFormerPage();
            }
            if(stripos($_SERVER['HTTP_REFERER'], "closer_commodity/index")>0){
                ic_rememberFormerPage();
            }
            $ruleid = I('id');
            if (empty($ruleid)) {
                $this->error('缺失主键');
            }
            $join = 'left join eosi_weixin_user ON eosi_bh_closet_commodity.uid = eosi_weixin_user.id';
            $joinad ='left join eosi_bh_type ON eosi_bh_closet_commodity.type = eosi_bh_type.id';
            $ab ='eosi_bh_closet_commodity.img as aimg,eosi_bh_type.img asbimg,
                eosi_bh_closet_commodity.name as aname,eosi_bh_type.name as bname,
                eosi_weixin_user.nickname,eosi_bh_closet_commodity.*';
            $map = array();
            $map['eosi_bh_closet_commodity.id'] = $ruleid;
            $data = M('bh_closet_commodity')->join($join)->join($joinad)->where($map)->Field($ab)->find();
            if (empty($data)) {
                $this->error('数据不存在');
            }
            $data['dh_date'] = date('Y-m-d ', $data['dh_date']);

            $data['sub_img_arr']=array();
            if(ic_checkUnEmpty($data['sub_imgs'])){
                $data['sub_imgs'] =explode(',',$data['sub_imgs']);
                
                foreach ($data['sub_imgs'] as $key => &$value) {
                    $tmp=ic_getUploadImgFullPath('commodity',$value,$data['create_time']);
                    $data['sub_img_arr'][]=array('url'=>$tmp,'realName'=>$value);
                    $value=$tmp;
                }
            }
            $data['img'] =  ic_getUploadImgFullPath('commodity',$data['aimg'],$data['create_time']);
            $mapto=array();
            $mapto['id']=array('neq', '1');
            $this->new_type =M('bh_type');
            $dataListopt =$this->new_type->where($mapto)->select();
            // var_dump($dataListopt);
            $this->assign('_listopt', $dataListopt);
            $this->assign('data', $data);
            $this->assign('datasub', $data['sub_imgs']);
            $this->assign('sub_img_arr', $data['sub_img_arr']);
            $this->assign('datasubstr', implode(',', $data['sub_imgs']));
            $this->assign('groupName', '商品管理 ');
            $this->assign('moduleName', '商品列表');
            $this->assign('actionName', '编辑商品');
            $this->display('CloserCommodity:editRule');
        }
    //更新规则
    public function updateRule() {
        try {
                $ruleid = I('id');
                if (empty($ruleid)) {
                    $this->error('缺失主键');
                }
                $type = I('type');
                $p_new_pic =I('p_new_pic');
                $status = I('status');
                $aname = I('aname');
                $memo = I('memo');
                $price = I('price');
                $dh_date = I('J-xl');
                $no = I('no');
                $sub_imgs =I('new_img');
                $show_order=I('show_order',100);

                $map = array();
                $map['id'] = $ruleid;
                $saveData = array();
                // $saveData['id'] = $ruleid;
                $saveData['type'] = $type;
                //perry 注释下面2句，在上传图片时已经实时更新表数据了，此处无需再更新
                // $saveData['img'] = $p_new_pic;
                // $saveData['sub_imgs'] = $sub_imgs;
                //end perry
                $saveData['name'] = $aname;
                $saveData['price'] = $price;
                $saveData['dh_date'] = strtotime($dh_date);
                $saveData['status'] = $status;
                $saveData['memo'] = $memo;
                $saveData['no'] = $no;
                $saveData['update_time'] =time();
                $saveData['show_order'] = $show_order;
                $saveData['color'] = I('color','');
                $saveData['size'] = I('size','');
                // var_dump($saveData);die;
                $flag = M('bh_closet_commodity')->where($map)->save($saveData);
                // dump(M('bh_closet_commodity')->getLastSql());
                if ($flag) {
                    $this->success('商品编辑成功,正在跳转请稍候……', ic_backToFormerPage('/Admin/CloserCommodity/index'));
                    // $this->success('规则编辑成功');
                    // $this->success('商品编辑成功', __CONTROLLER__ . '/editRule'.'/id/'.$ruleid);
                } else {
                    $this->error('商品编辑失败，是否未做修改，请检查.');
                }
            }catch (Exception $exc) {
                    $ajaxdata['info'] = $exc->getMessage();
                    $ajaxdata['status'] = 400;
                    $this->ajaxReturn($ajaxdata);
            }
    }

    //上传单品图片
    public function uploadImg() {
        
       try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_closet_commodity')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('commodity',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {

                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                foreach ($uploadList as $key => $value) {
                    echo "<script>
                    parent.document.getElementById('img').style.display='';
                    parent.document.getElementById('img').src='" . ic_getUploadImgFullPath('commodity',$value['savename'],$ctime) . "';
                    parent.document.getElementById('p_new_pic').value='" . $value['savename'] . "';
                    </script>";
                    //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                    if($exist){
                        // $oldfilePath=ic_getUploadImgServerPath('commodity',$exist['create_time']);
                        $this->delMulti($exist['img'],$ctime);
                        $data=array('img'=>$value['savename'],'update_time'=>time());
                        M('bh_closet_commodity')->where($map)->save($data);
                    }
                }   
            }
            // $img_arr = [];
            // $upload = new \Think\Upload();// 实例化上传类
            // $upload->maxSize   =     3145728 ;// 设置附件上传大小
            // $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            // $upload->rootPath  =     './Public/Uploads/img/'; // 设置附件上传根目录
            // $upload->savePath  =     ''; // 设置附件上传（子）目录
            // $upload->autoSub  =     false; // 设置附件上传（子）目录
            // // $upload->saveName = 'time';
            // // 上传文件 
            // $info   =   $upload->upload();
            // if(!$info) {
            //     // 上传错误提示错误信息
            //     echo "<script>parent.art.dialog.alert('" . $upload->getError() . "');</script>";
            //     exit;
            // }else{
            //     // 上传成功
            //     foreach ($info as $key => $value) {
            //         $image = new \Think\Image();
            //         $image->open('./Public/Uploads/img/' . $value['savename']);
            //         // $value['ext'] 图片后缀名
            //         $new_file_name = $this->getMillisecond() . '.' . $value['ext'];
            //         $image->save('./Public/Uploads/img/' . $new_file_name);
            //         @unlink('./Public/Uploads/img/' . $value['savename']);
            //         $img_arr[] = $new_file_name;
            //         //删除之前的图片
            //         @unlink('./Public/Uploads/img/' . I('p_new_pic'));
            //         echo "<script>parent.document.getElementById('img').style.display='';parent.document.getElementById('img').src='" . __APP__ . '/Public/Uploads/img/' . $new_file_name . "';parent.document.getElementById('p_new_pic').value='" . $new_file_name . "';</script>";
            //     }
            // }
        }catch (Exception $exc) {
            //返回失败信息
            echo "<script>parent.art.dialog.alert('" . $exc->getMessage() . "');</script>";
            exit;
        }
    }

    //上传商品关联图片
    public function upload() {
        try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_closet_commodity')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('commodity',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                $img_arr=array();
                $img_arr_with_oriNmae=array();
                foreach ($uploadList as $key => $value) {
                    $img_arr[]=$value['savename'];
                }
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                $ajaxdata['info'] = implode(',', $img_arr);
                //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                if($exist){
                    // $oldfilePath=ic_getUploadImgServerPath('commodity',$exist['create_time']);
                    // $tmparr=explode(',',$exist['sub_imgs']);
                    // foreach ($tmparr as $key => $value) {
                    //     $this->delMulti($oldfilePath,$value);
                    // }
                    if($exist['sub_imgs']){
                        $ajaxdata['info']=sprintf("%s,%s",$exist['sub_imgs'],$ajaxdata['info']);
                    }
                    
                    $data=array('sub_imgs'=>$ajaxdata['info'],'update_time'=>time());
                    M('bh_closet_commodity')->where($map)->save($data);
                }
                
                $ajaxdata['status'] = 1;
                $this->ajaxReturn($ajaxdata);
                
            }

            // $img_arr = [];
            // $upload = new \Think\Upload();// 实例化上传类
            // $upload->maxSize   =     3145728 ;// 设置附件上传大小
            // $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            // $upload->rootPath  =     ic_getUploadImgServerPath('commodity',time());  //'./Public/Uploads/sub_imgs/'; // 设置附件上传根目录
            // $upload->savePath  =     ''; // 设置附件上传（子）目录
            // $upload->autoSub  =     false; // 设置附件上传（子）目录
            // // $upload->saveName = 'time';
            // // 上传文件 
            // $info   =   $upload->upload();
            // if(!$info) {
            // // 上传错误提示错误信息
            //     $ajaxdata['info'] = $upload->getError();
            //     $ajaxdata['status'] = 400;
            //     $this->ajaxReturn($ajaxdata);
            // }else{
            // // 上传成功
            //     foreach ($info as $key => $value) {
            //         $image = new \Think\Image();
            //         $image->open('./Public/Uploads/sub_imgs/' . $value['savename']);
            //         // $value['ext'] 图片后缀名
            //         $new_file_name = $this->getMillisecond() . '.' . $value['ext'];
            //         $image->save('./Public/Uploads/sub_imgs/' . $new_file_name);
            //         @unlink('./Public/Uploads/sub_imgs/' . $value['savename']);
            //         $img_arr[] = $new_file_name;
            //     }
            //     $ajaxdata['info'] = implode(',', $img_arr);
            //     $ajaxdata['status'] = 1;
            //     $this->ajaxReturn($ajaxdata);
            // }
        }catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }

    //编辑商品时删除幅图
    public function uploadDelete(){
        $exist=false;
        $skey=I('session_key',false);
        if($skey===false){
            $id=I('id',false);
            if(!ic_isPosInt($id)){
                return;
            }
            else {
                $map=array('id'=>$id);
                $exist=M('bh_closet_commodity')->where($map)->find();
                if(!$exist){
                    return;
                }
                $ctime=$exist['create_time'];
            }
        }
        else {
            $ctime=$_SESSION[$skey."_time"];
        }

        $delName=I('realName',false);
        if($delName===false){
            return;
        }

        if($exist){
            //是来自编辑页面的删除，需要实时保存到数据表
            $oldNames=explode(",", $exist['sub_imgs']);
            $newNames=array();
            foreach ($oldNames as $key => $value) {
                if($value!=$delName){
                    $newNames[]=$value;
                }
            }
            $newNames=implode(",", $newNames);
            $data['update_time']=time();
            $data['sub_imgs'] = $newNames;
            M('bh_closet_commodity')->where($map)->save($data);
        }
        $this->delMulti($delName,$ctime);
    }

    private function delMulti($delName,$ctime=0){

        //当前栏目为商品衣橱，type=1
        $objType=1;
        //物理删除前先判断该图片是否被其它造型使用
        $picM=D('MultiUploadPic');
        $used=$picM->findUsedRecords($delName,$objType);
        if(!$used['used']){
            $serverPath=ic_getUploadImgServerPath("commodity",$ctime);
            @unlink($serverPath.$delName);
            @unlink($serverPath."m_".$delName);
            @unlink($serverPath."s_".$delName);
            //删除批量图片表里的存储记录
            if($ctime==C("img_multi_create_time")){
                $umap=array('uni_name'=>$delName,'type'=>$objType);
                $aa=$picM->where($umap)->delete();
            }
        }
        
    }

    private function renameMulti($serverPath,$newName,$oldName,$ctime=0){
        $this->delMulti($oldName,$ctime);
        rename($serverPath.$newName, $serverPath.$oldName);
        rename($serverPath."m_".$newName, $serverPath."m_".$oldName);
        rename($serverPath."s_".$newName, $serverPath."s_".$oldName);
    }

    //从session取得旧图片信息并删除
    private function deleteOld(){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $oldFiles=$_SESSION[$skey];
        if(!$oldFiles){
            return;
        }
        foreach ($oldFiles as $key => $value) {
            // $serverPath=ic_getUploadImgServerPath("commodity",$_SESSION[$skey."_time"]);
            // @unlink($serverPath.$value['savename']);
            // @unlink($serverPath."m_".$value['savename']);
            // @unlink($serverPath."s_".$value['savename']);
            $this->delMulti($value['savename'],$_SESSION[$skey."_time"]);
        }
    }

    private function saveOldFIleSession($arr,$ctime){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $_SESSION[$skey]=$arr;
        $_SESSION[$skey."_time"]=$ctime;
    }

    public function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
    //添加规则
    public function addRule() {
        ic_rememberFormerPage();
        $mapto=array();
        $mapto['id']=array('neq', '1');
        $this->new_type =M('bh_type');
        $dataListopt =$this->new_type->where($mapto)->select();
        $this->assign('_listopt', $dataListopt);
        $this->assign('groupName', '商品管理 ');
        $this->assign('moduleName', '商品列表');
        $this->assign('actionName', '添加商品');
        $this->display('CloserCommodity:addRule');

    }
    //保存规则
    public function insertRule() {
        // var_dump(I());die;
        $uid = 999;
        // var_dump($uid);
        $type = I('type');
        $p_new_pic = I('p_new_pic');
        $status = I('status');
        $name = I('name');
        $Jxl = I('J-xl');
        $price =I('price');
        // $name = I('name');
        $memo = I('memo');
        $sub_imgs = I('new_img');
        $no = I('no');
        $show_order = I('show_order',100);

        $saveData = array();
        $saveData['uid'] = $uid;
        $saveData['type'] = $type;
        $saveData['img'] = $p_new_pic;
        $saveData['status'] = $status;
        $saveData['name'] = $name;
        $saveData['memo'] = $memo;
        $saveData['sub_imgs'] = $sub_imgs;
        $saveData['no'] = $no;
        $saveData['dh_date'] = strtotime($Jxl);
        $saveData['price'] = $price;
        $saveData['create_time'] = time();
        $saveData['update_time'] = time();
        $saveData['show_order'] = $show_order ;
        $saveData['color'] = I('color','');
        $saveData['size'] = I('size','');
        // var_dump($saveData);

        $flag = M('bh_closet_commodity')->add($saveData);
        if ($flag) {
            // $this->success('规则添加成功', __CONTROLLER__ . '/rule'.'/id/'.$flag);
            $this->success('商品添加成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));

        } else {
            $this->error('商品添加失败');
        }
    }
    // 保存成功 显示
      public function rule() {
        
        $map = array();
        $map['id'] = $_GET['id'];
        $data = M('bh_closet_commodity')->where($map)->select();
        $data[0]['create_time'] = date('Y-m-d H:i:s', $data[0]['create_time']);
        $data[0]['sub_imgs'] = explode(',', $data[0]['sub_imgs']);
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
      //状态
        if ($data[0]['status'] == 1) {
            $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\">" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" style=\"cursor: pointer;\" title=\"禁用\" index='" . $value['id'] . "' ></span>";
        }else{
            $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" style=\"cursor: pointer;\" title=\"启用\"  index='" . $value['id'] . "' ></span>";
        }
        $this->assign('data_data', $data);
        $this->new_type =M('bh_type');
        $dataListopt =$this->new_type->select();
        $this->assign('_listopt', $dataListopt);
        $this->assign('groupName', '商品管理 ');
        $this->assign('moduleName', '商品列表');
        $this->assign('actionName', '商品显示');
        $this->display('CloserCommodity:rule');
        // dump($data);
        // dump($data[0]['sub_imgs']);

    }
    //删除规则
    public function deleteRule() {

        ic_rememberFormerPage();
        $ruleid = I('id');
        if (empty($ruleid)) {
            $this->error('缺失主键');
        }
        $mapexist=array('id'=>$ruleid);
        $exist=M('bh_closet_commodity')->where($mapexist)->find();
        //删除规则表   
            if($exist){
                $flag = M('bh_closet_commodity')->where("id={$ruleid}")->delete();
                if ($flag) {
                    $itemType=I('itemtype','commodity');
                    // $serverPath=ic_getUploadImgServerPath($itemType,$exist['create_time']);
                    $this->delMulti($exist['img'],$exist['create_time']);
                    //如果有附图，附图也要删除
                    if($exist['sub_imgs']){
                        $arr= explode(",", $exist['sub_imgs']);
                        foreach ($arr as $key => $value) {
                            $this->delMulti($value,$exist['create_time']);
                        }
                    }
                    $this->success('删除成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));
                }else{
                    $this->error('删除规则失败');
                    
            }
        } else {
            $this->error('待删除数据已不存在，请刷新页面重试');
        }
    }
    // 非管理员用户------------------------------------------------------------------------------
     //用户列表
    public function closer() {
        $this->user_model = M('bh_closet_commodity');
        $join = 'left join eosi_weixin_user ON eosi_bh_closet_commodity.uid = eosi_weixin_user.id';
        $joinad ='left join eosi_bh_type ON eosi_bh_closet_commodity.type = eosi_bh_type.id';
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
        $map=array();
        if($_GET['nickname']!=''){
            $map['eosi_weixin_user.nickname']=array('like', '%'.$_GET['nickname'].'%');
        }
        if($_GET['aname']!=''){
             $map['eosi_bh_closet_commodity.name']=array('like', '%'.$_GET['aname'].'%');
        }
        if($_GET['bname']!='' && $_GET['bname']!= 1){
             $map['eosi_bh_type.id']=$_GET['bname'];
        }
        if($_GET['memo']!=''){
             $map['eosi_bh_closet_commodity.memo']=array('like', '%'.$_GET['memo'].'%');
        }

        $map['eosi_bh_closet_commodity.uid']=array('neq', '999');;
        // $map['eosi_bh_closet_commodity.uid'] !=999;
        // var_dump($map);exit;    
        //任务总数
        $total = $this->user_model->join($join)->join($joinad)->where($map)->count();
        //每页条数
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        //实例化分页类
        $page = new \Admin\ORG\PageNew($total, $listRows, '');
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');     
        $ab ='eosi_bh_closet_commodity.img as aimg,eosi_bh_type.img as bimg,
                eosi_bh_closet_commodity.name as aname,eosi_bh_type.name as bname,
                eosi_weixin_user.nickname,eosi_bh_closet_commodity.*';
        $dataList = $this->user_model->join($join)->join($joinad)->where($map)->order('eosi_bh_closet_commodity.id desc')->limit("$page->firstRow,$page->listRows")->Field($ab)->select();
        // dump($dataList);
        $this->new_type =M('bh_type');
        $dataListopt =$this->new_type->select();
        //数据处理
        foreach ($dataList as $k => $value){
            $cctime=$value['create_time'];
            //状态
            if ($value['status'] == 1) {
                $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\" >" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" title=\"禁用\" style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }else{
                $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" title=\"启用\"  style=\"cursor: pointer;\" index='" . $value['id'] . "' ></span>";
            }
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['dh_date'] = date('Y-m-d ', $value['dh_date']);
            $value['dh_date'] = explode('-', $value['dh_date']);
            $c = $value['dh_date'][0];
            $a = $value['dh_date'][1];
            $a = preg_replace('/^0/', '', $a);
            $b = $value['dh_date'][2];
            $b = preg_replace('/^0/', '', $b);
            $value['dh_date'] =$c.'.'.$a.'.'.$b;
            // $map['eosi_bh_calendar.year']=array('like',$_GET['bname'][0]);
            // $map['eosi_bh_calendar.month']=array('like',$a);
            // $map['eosi_bh_calendar.day']=array('like',$b);

            $value['s_img'] =  ic_getUploadImgFullPath('closet', ic_getDiffSizeImg($value['aimg'],'thumb'),$cctime);
            $value['img'] =  ic_getUploadImgFullPath('closet', $value['aimg'],$cctime);
            
            $dataList[$k] = $value;
            $imgchild = array();
            if(ic_checkUnEmpty($value['sub_imgs'])){
                $value['sub_imgs'] =explode(',',$value['sub_imgs']); 
                foreach ($value['sub_imgs'] as $key => $v) {
                    $$imgchild[$key]=array();
                    $imgchild[$key]['s_img'] = ic_getUploadImgFullPath('commodity',ic_getDiffSizeImg($v,'thumb'),$cctime);
                    $imgchild[$key]['img'] = ic_getUploadImgFullPath('commodity',$v,$cctime);
                }
            }
            $dataList[$k]['sub_imgs_arr'] = $imgchild;
        }
        
        $this->assign('_listopt', $dataListopt);
        $this->assign('_list', $dataList);
        $this->assign('bname_id', $_GET['bname']);
        $this->assign('nickname', $_GET['nickname']);
        $this->assign('aname', $_GET['aname']);
        $this->assign('memo', $_GET['memo']);
        $this->assign('groupName', '衣橱管理');
        $this->assign('moduleName', '衣橱列表');
        $this->assign('actionName', '衣橱概览');
        // $this->assign('nickname',$array['nickname']);
        $this->display();
    }

    //根据上传的excel批量导入商品数据到表里
    public function ajaxImportMultiCommodity(){
        try {
            $ext = strrchr($_FILES["uploadExcelCommodityForm"]["name"], ".");
            if ($ext != ".xlsx")
                throw new \Exception('只允许上传xlsx类型的文件,请检查.');
            ini_set('memory_limit', '512M');
            //调用上传Excel表格数据
            $result = ic_uploadFile("xls,xlsx","commodity",false);
            // dump($result);
            // exit;
            $uploadfile = $result[0]["savepath"] . $result[0]["savename"]; //获取上传路径文件名
            $startRow=3;
            $info = ic_importFromExcel($uploadfile,$startRow,"C","N"); //读取EXCEL表格
            if(!$info)
                throw new \Exception('未从上传文件中读取到数据，请检查');
            M()->startTrans();
            //数据准备
            $tm =M('bh_type');
            $cm=M('bh_closet_commodity');
            $mapto=array();
            $mapto['id']=array('neq', '1');
            $bhTypes =$tm->where($mapto)->field("id,name")->select();
            $cbhTypes=array();
            foreach ($bhTypes as $key => $value) {
                $cbhTypes[$value['name']]=$value;
            }
            $errMsg="";
            $succmsg="";
            $nl="\r\n";
            $picM=D('MultiUploadPic');
            $img_multi_hz=C('img_multi_hz');
            $img_multi_create_time=C('img_multi_create_time');
            $datas=array();
            $noUniArr=array();
            //开始插入或更新数据
            foreach ($info as $key => $value) {
                $c=array();
                //唯一编号
                $c['no']=$value[8];
                if(!ic_checkUnEmpty($c['no'])){
                    $errMsg.=sprintf("第%d行编号不能为空,请完善.%s",$startRow+$key,$nl);
                    //没有编号，直接中断
                    break;
                }
                if(array_key_exists($c['no'], $noUniArr)){
                    $errMsg.=sprintf("第%d行编号和第%d行编号重复了，请修改.%s",$startRow+$key,$noUniArr[$c['no']],$nl);
                    //编号重复了
                    break;
                }
                $noUniArr[$c['no']]=$startRow+$key;
                //本条数据是否标识为物理删除 N列
                $is_delete=$value[11];
                if(strtolower(trim($is_delete))=='y'){
                    $exist=$cm->where('no="'.$c['no'].'"')->find();
                    if(!$exist){
                        //$errMsg.=sprintf("第%d行编号%s指定删除，但系统中并无该数据，请检查.%s",$startRow+$key,$c['no'],$nl);
                        //没有编号，直接中断
                        //break;
                        //没有找到待删除编号，continue
                        continue;
                    }
                    
                    //删除表数据
                    //删除商品数据
                    $aaa=$cm->where('id='.$exist['id'])->delete();
                    if($aaa){
                        //删除物理图片
                        // $serverPath=ic_getUploadImgServerPath("commodity",$exist['create_time']);
                        $this->delMulti($exist['img'],$exist['create_time']);
                        if(ic_checkUnEmpty($exist['sub_imgs'])){
                            $tmpsubArr=explode(",", $exist['sub_imgs']);
                            foreach ($tmpsubArr as $simg) {
                                $this->delMulti($simg,$exist['create_time']);
                            }
                        }
                        //删除批量导入图片信息
                        $picM->where(array('uni_name'=>$exist['img'].$img_multi_hz,'type'=>1))->delete();
                    }
                    $succmsg.=sprintf("第%d行编号%s成功删除.%s",$startRow+$key,$exist['no'],$nl);
                    //乐娇超说客户暂不要求删除使用本商品的造型数据
                    continue;
                }
                
                $c['uid']=999;

                //状态
                $status_str=(string)$value[4];
                if($status_str==="0"||$status_str==="1"||$status_str==="-1"){
                    $c['status']=$value[4];
                }
                else {
                    $c['status']=1;
                }

                //类型
                if(!array_key_exists($value[0],$cbhTypes )){
                    $errMsg.=sprintf("第%d行类型值不对,%s",$startRow+$key,$nl);
                    // continue;
                }
                else {
                    $c['type']=$cbhTypes[$value[0]]['id'];
                }
                //显示顺序
                $c['show_order']=$value[1];
                if(!ic_isPosInt($value[1] )){
                    $c['show_order']=1000;
                }

                //商品首图
                if(ic_checkUnEmpty($value[2])){
                    $uploadedPic=$picM->getByOriName($value[2]);
                    if(!$uploadedPic){
                        $errMsg.=sprintf("第%d行商品首图有指定:%s，但图未上传,%s",$startRow+$key,$value[2],$nl);
                        // continue;
                    }
                    else {
                        $c['img']=$uploadedPic['uni_name'];
                        $c['create_time']=$img_multi_create_time; //创建时间和图片上传时间一致，才能正确定位图片子目录ymd
                    }
                }
                else {
                    $c['img']='';
                    if($c['status']==1){
                        //如果用户excel指定了状态为启用，但因为缺图，系统不得不将状态改成-1缺图
                        $c['status']=-1; //缺图
                    }
                    $c['create_time']=$img_multi_create_time; //创建时间和图片上传时间一致，才能正确定位图片子目录ymd
                }

                //商品其它幅图
                if(ic_checkUnEmpty($value[3])){
                    $sub_imgs=explode(",", $value[3]);
                    $allGood=true;
                    $subArr=array();
                    foreach ($sub_imgs as $key2 => $value2) {
                        $uploadedPic=$picM->getByOriName($value2);
                        if(!$uploadedPic){
                            $errMsg.=sprintf("第%d行商品副图有指定:%s，但图未上传,%s",$startRow+$key,$value2,$nl);
                            $allGood=false;
                            // continue;
                        }
                        else{
                            $subArr[]=$uploadedPic['uni_name'];
                        }
                    }
                    if($allGood){
                        $c['sub_imgs']=implode(",", $subArr);
                        $c['create_time']=$img_multi_create_time; //创建时间和图片上传时间一致，才能正确定位图片子目录ymd
                    }
                    
                }
                else {
                    $c['sub_imgs']="";

                    $c['create_time']=$img_multi_create_time; //创建时间和图片上传时间一致，才能正确定位图片子目录ymd
                }

                //名称
                $c['name']=$value[5];
                //附注
                $c['memo']=$value[6];
                //商品价格
                $c['price']=$value[7];
                
                //款色
                $c['color']=$value[9];
                //尺码
                $c['size']=$value[10];
                if($errMsg!==''){
                    break;
                }
                $c['update_time']=time();
                $datas[]=$c;
                $editMode='更新';
                $exist=$cm->field('id')->where('no="'.$c['no'].'"')->find();
                if(!$exist){
                    $editMode='新增';
                }
                $succmsg.=sprintf("第%d行编号%s成功%s.%s",$startRow+$key,$exist['no'],$editMode,$nl);
            }
            //利用addAll第3参数特性，唯一键no重复则更新，否则新增
            if($errMsg==''){
                // dump($datas);
                // exit;
                $re=$cm->addAll($datas,array(),array('update_time','create_time','uid','status','type','show_order','img','sub_imgs','name','memo','price','color','size'));
                $logName='succ_'.time().".txt";
                file_put_contents(ic_getUploadImgServerPath('commodity',false).$logName, $succmsg);
            }
            else {
                $logName=time().".txt";
                file_put_contents(ic_getUploadImgServerPath('commodity',false).$logName, $errMsg);
                
                throw new \Exception(ic_getUploadImgFullPath('commodity',$logName,false), -1);
                
            }
            M()->commit();
            $data['error'] = 'false';
            $data['msg'] =  ic_getUploadImgFullPath('commodity',$logName,false);
            echo json_encode($data);
        } catch (\Exception $ex) {
            M()->rollback();
            $data['error'] = 'true';
            $data['msg'] = $ex->getMessage();
            echo json_encode($data);
        }
    }

    //批量上传多张图片第一步，把多张图片保存到服务器
    //返回服务器保存的新文件名和图片原文件名
    //，create_time必须写死才能找到正确子目录
    public function multiUploadPic(){
        $ctime=C('img_multi_create_time');
        try {
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 200*1024*1024;
            //设置上传文件类型
            // $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            $upload->allowExts          = explode(',', 'png');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('commodity',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
                throw new \Exception($upload->getErrorMsg());
                
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                $img_arr=array();
                $img_arr_with_oriNmae=array();
                $datas=array();
                $uM=M('bh_multi_upload_pic');
                foreach ($uploadList as $key => $value) {
                    $data=array();
                    $data['type']=1; //1代表commodity,2代表造型图
                    $data['ori_name']=$value['name'];
                    $data['uni_name']=$value['savename'];
                    $data['create_time']=time();
                    $data['update_time']=time();
                    //如果已存在则要把savename替换成和表里的uni_name一致
                    $umap=array('ori_name'=>$data['ori_name'],'type'=>$data['type']);
                    $existPic=$uM->where($umap)->find();
                    if($existPic){
                        $this->renameMulti(ic_getUploadImgServerPath('commodity',$ctime),$data['uni_name'],$existPic['uni_name'],$ctime);
                        $value['savename']=$existPic['uni_name'];
                        // continue;
                        $data['uni_name']=$existPic['uni_name'];
                    }  
                    $datas[]=$data;                
                    $img_arr[]=$value['savename'];
                    $img_arr_with_oriNmae[]=$value['savename'];
                    $img_arr_with_oriNmae[]=$value['name'];
                }
                if($datas){
                    $flag=$uM->addAll($datas,array(),array('type','uni_name','update_time'));
                }
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                $ajaxdata['info'] = implode(',', $img_arr);
                $ajaxdata['infoMore'] = implode(',', $img_arr_with_oriNmae);
                
                $ajaxdata['status'] = 1;
                $this->ajaxReturn($ajaxdata);
                
            }
        }catch (\Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }

    //批量上传多张图片第二步，把多张已上传到服务器的文件名信息
    //批量插入或更新数据到eosi_bh_multi_upload_pic表
    public function multiUpload(){
        $this->success('批量导入图片成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));
        // $new_img=I('new_img');                            //59ddc98c96ed4.JPG,59ddc98cedd88.JPG
        // $niarray=explode(",", $new_img);
        // $new_img_with_oriName=I('new_img_with_ori_name'); //59ddc98c40408.JPG,IMG_4200.JPG,59ddc98c96ed4.JPG,IMG_4404.JPG,59ddc98cedd88.JPG,IMG_4409.JPG
        // $niwoArr=explode(",", $new_img_with_oriName);
        // // dump($niwoArr);
        // $niwoArr2=array();
        // for($i=0;$i<=count($niwoArr)-2;$i+=2){
        //     $niwoArr2[$niwoArr[$i]]=$niwoArr[$i+1];
        // }
        // $mupicTypeSelect=I('mupicTypeSelect',1);
        // // dump($niwoArr2);
        // $datas=array();
        // $uM=M('bh_multi_upload_pic');
        // $ctime=C('img_multi_create_time');
        // foreach ($niarray as $key => $value) {
        //     $data=array();
        //     $data['type']=$mupicTypeSelect; //1代表commodity,2代表造型图
        //     $data['ori_name']=strtolower($niwoArr2[$value]);
        //     $data['uni_name']=$value;
        //     //到eosi_bh_multi_upload_pic判断同样name的图片是否存在，
        //     //如果已存在则要把savename替换成和表里的uni_name一致
        //     // $umap=array('ori_name'=>$data['ori_name']);
        //     $umap=array('ori_name'=>$data['ori_name'],'type'=>$mupicTypeSelect);
        //     $existPic=$uM->where($umap)->find();
        //     if($existPic){
        //         $this->renameMulti(ic_getUploadImgServerPath('commodity',$ctime),$data['uni_name'],$existPic['uni_name']);
        //         continue;
        //     }
        //     $data['create_time']=time();
        //     $data['update_time']=time();
        //     $datas[]=$data;
        // }
        // // dump($datas);
        // // exit;
        // $flag=true;
        // if($datas){
        //     $flag=$uM->addAll($datas,array(),array('type','uni_name','update_time'));
        // }
        // if ($flag) {
        //     // $this->success('规则添加成功', __CONTROLLER__ . '/rule'.'/id/'.$flag);
        //     $this->success('批量导入图片成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));

        // } else {
        //     $this->error('批量导入图片失败');
        // }
    }
  
    //批量上传多张图片入口页
    public function multiuploadimg2(){
        $this->display();
    }

}
